package com.sk.netty.udpclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;


import java.net.InetSocketAddress;

public class EchoUdpClient {

    public static void main(String[] args) throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                    @Override
                    public void channelRead0(ChannelHandlerContext ctx,
                            DatagramPacket msg) throws Exception{
                        System.out.println(msg.content().toString(CharsetUtil.UTF_8));
                    }
                });
        ChannelFuture future = bootstrap.bind(0).sync();
        Channel channel = future.channel();

        DatagramPacket packet = new DatagramPacket(Unpooled.copiedBuffer("你好upd客户发来贺电".getBytes(CharsetUtil.UTF_8)),new InetSocketAddress("127.0.0.1",19090));

        channel.writeAndFlush(packet).sync();

    }
}
